package top.linyuxb.lycloud.admin.controller;

import jakarta.annotation.Resource;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.linyuxb.lycloud.admin.constant.StatusEnum;
import top.linyuxb.lycloud.admin.entity.LyCloudUserEntity;
import top.linyuxb.lycloud.admin.entity.LyConfProjectEntity;
import top.linyuxb.lycloud.admin.repository.LyConfNodeRepository;
import top.linyuxb.lycloud.admin.repository.LyConfProjectRepository;
import top.linyuxb.lycloud.admin.service.ILyConfPermissionService;
import top.linyuxb.lycloud.admin.service.impl.LoginService;
import top.linyuxb.lycloud.admin.utils.ReturnT;
import top.linyuxb.lycloud.admin.web.annotation.PermissionLimit;

import java.util.*;

import static top.linyuxb.lycloud.admin.web.interceptor.EnvInterceptor.CURRENT_ENV;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/29 14:43
 * @Desc: 项目管理
 */
@Controller
@RequestMapping("/project")
public class ProjectController {

    @Resource
    private LyConfProjectRepository lyConfProjectRepository;
    @Resource
    private LyConfNodeRepository lyConfNodeRepository;
    @Resource
    private ILyConfPermissionService lyConfPermissionService;

    @RequestMapping
    public String index(HttpServletRequest request, Model model) {
        LyCloudUserEntity lyCloudUser = (LyCloudUserEntity) request.getAttribute(LoginService.LOGIN_IDENTITY);
        List<LyConfProjectEntity> list = lyConfProjectRepository.findByStatusOrderByIdDesc(StatusEnum.VALID.getType());
        Set<String> apps = new HashSet<>();
        Boolean status = lyConfPermissionService.getPermissionApps(lyCloudUser, apps);
        list.removeIf(server -> !status && !apps.contains(server.getApp()));
        model.addAttribute("list", list);
        return "project/project.index";
    }

    @ResponseBody
    @RequestMapping("/save")
    @PermissionLimit(adminuser = true)
    public ReturnT<String> save(LyConfProjectEntity lyConfProject) {
        // valid
        if (StringUtils.isBlank(lyConfProject.getApp())) {
            return new ReturnT<>(500, "AppName不可为空");
        }
        if (lyConfProject.getApp().length() < 4 || lyConfProject.getApp().length() > 100) {
            return new ReturnT<>(500, "Appname长度限制为4~100");
        }
        if (StringUtils.isBlank(lyConfProject.getTitle())) {
            return new ReturnT<>(500, "请输入项目名称");
        }

        // valid repeat
        LyConfProjectEntity existProject = lyConfProjectRepository.findByApp(lyConfProject.getApp());
        if (existProject != null) {
            return new ReturnT<>(500, "Appname已存在，请勿重复添加");
        }

        lyConfProjectRepository.save(lyConfProject);
        return ReturnT.SUCCESS;
    }

    @ResponseBody
    @RequestMapping("/update")
    @PermissionLimit(adminuser = true)
    public ReturnT<String> update(LyConfProjectEntity lyConfProject) {
        // valid
        if (StringUtils.isBlank(lyConfProject.getApp())) {
            return new ReturnT<>(500, "AppName不可为空");
        }
        if (StringUtils.isBlank(lyConfProject.getTitle())) {
            return new ReturnT<>(500, "请输入项目名称");
        }

        lyConfProjectRepository.save(lyConfProject);
        return ReturnT.SUCCESS;
    }

    @ResponseBody
    @RequestMapping("/remove")
    @PermissionLimit(adminuser = true)
    public ReturnT<String> remove(String app) {
        if (StringUtils.isBlank(app)) {
            return new ReturnT<>(500, "参数AppName非法");
        }
        // valid
        int list_count = (int) lyConfNodeRepository.count(
                (root, criteriaQuery, cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if (StringUtils.isNotBlank(app)) {
                        predicates.add(cb.equal(root.get("app").as(String.class), app));
                    }
                    return cb.and(predicates.toArray(new Predicate[0]));
                }
        );
        if (list_count > 0) {
            return new ReturnT<>(500, "拒绝删除，该项目下存在配置数据");
        }

        List<LyConfProjectEntity> allList = lyConfProjectRepository.findByStatusOrderByIdDesc(StatusEnum.VALID.getType());
        if (allList.size() == 1) {
            return new ReturnT<>(500, "拒绝删除, 需要至少预留一个项目");
        }

        int ret = lyConfProjectRepository.deleteByApp(app);
        return (ret > 0) ? ReturnT.SUCCESS : ReturnT.FAIL;
    }

}
